package cn.zlj.pethome.order.service.impl;

import cn.zlj.pethome.basic.config.BussinessException;
import cn.zlj.pethome.basic.dto.PayDto;
import cn.zlj.pethome.basic.util.CodeGenerateUtils;
import cn.zlj.pethome.order.domain.OrderProduct;
import cn.zlj.pethome.order.mapper.OrderProductMapper;
import cn.zlj.pethome.order.service.IOrderProductService;
import cn.zlj.pethome.basic.service.impl.BaseServiceImpl;
import cn.zlj.pethome.product.domain.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zlj
 * @since 2022-11-03
 */
@Service
public class OrderProductServiceImpl extends BaseServiceImpl<OrderProduct> implements IOrderProductService {
    @Autowired
    private OrderProductMapper orderProductMapper;

    @Override
    public void shopping(Product product) {
        System.out.println(product.getUserId());
        //生成订单服务 给服务的订单量+1
        OrderProduct orderProduct = new OrderProduct();
        orderProduct.setUserId(product.getUserId());
        orderProduct.setShopId(product.getShop().getId());
        orderProduct.setProductId(product.getId());
        orderProduct.setPrice(product.getSaleprice());
        orderProduct.setDigest("【服务订单]购买一次" + product.getName());
        orderProduct.setState(3);
        orderProduct.setOrderSn(CodeGenerateUtils.generateOrderSn(product.getId()));
        orderProduct.setPaySn(CodeGenerateUtils.generateUnionPaySn());
        orderProduct.setLastPayTime(new Date());
        super.add(orderProduct);
    }

    @Override
    public void cancel(Long id) {
        orderProductMapper.cancel(id);
        //加入日志。。
    }

    @Override
    public void confirm(PayDto payDto) {
        OrderProduct or = orderProductMapper.findById(payDto.getId());
        if (or == null || or.getState() != 3) {
            throw new BussinessException("该订单不能确认为异常状态");
        }
        synchronized (payDto.getId()){
            //!or.getShop().equals(payDto.getEmployee())||
            if(or.getState()==-1||or.getState()==1){
                throw new BussinessException("该订单不能确认为异常状态2");
            }
            or.setPrice(new BigDecimal(payDto.getMoney()));
            or.setPayType(payDto.getPayType());
            or.setState(1);
            super.update(or);
        }
//添加日志
    }
}
